package com.sxt.bus.controller;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sxt.bus.service.CarService;
import com.sxt.bus.vo.CarVo;
import com.sxt.sys.utils.DataGridView;
import com.sxt.sys.utils.WebUtils;

@Controller
@RequestMapping("car")
public class CarController {
    @Autowired
    private CarService carService;
		
		/**
		 * 跳转到客户管理的页面
		 */
		@RequestMapping("toCarManager")
		public String toCarManager(){
			return "business/carManager";
		}
		/**
		 * 查询
		 */
		@RequestMapping("loadAllCar")
		@ResponseBody
		public DataGridView loadAllCar(CarVo carVo){
			/*DataGridView dg = this.carService.queryAllCar(carVo);
			System.out.println(dg.getTotal());*/
			return  this.carService.queryAllCar(carVo);
		}
		@RequestMapping("addCar")
		@ResponseBody
		public Map<String,Object> addCar(CarVo carVo){
			Map<String,Object> map=new HashMap<>();
			 try {
				 this.carService.addCar(carVo);
				 map.put("msg", "添加成功");
			} catch (Exception e) {
				e.printStackTrace();
				 map.put("msg", "添加失败");
			}
			return  map;
		}
		@RequestMapping("updateCar")
		@ResponseBody
		public Map<String,Object> updateCar(CarVo carVo){
			Map<String,Object> map=new HashMap<>();
			 try {
				 this.carService.updateCar(carVo);
				 map.put("msg", "修改成功");
			} catch (Exception e) {
				e.printStackTrace();
				 map.put("msg", "修改失败");
			}
			return  map;
		}
		
		//删除
		/*@RequestMapping("deleteCar")
		@ResponseBody
		public Map<String,Object> deleteCar(CarVo carVo){
			Map<String,Object> map=new HashMap<>();
			 try {
				 this.carService.deleteCar(carVo);
				 map.put("msg", "添加成功");
			} catch (Exception e) {
				e.printStackTrace();
				 map.put("msg", "添加失败");
			}
			return  map;
		}*/
		//删除
		@RequestMapping("deleteCar")
		@ResponseBody
		public Map<String,Object> deleteCar(CarVo carVo){
			Map<String,Object> map=new HashMap<>();
			 try {
				 //1.删除图片
				//获取数据库中保存的路径 ：../upload/2018-11-25等等.jpg
				 String path=carVo.getCarimg();
				 if(null!=path&&!path.equals("")){
					 String realPath=WebUtils.getServletContext().getRealPath("/");
					 String factPath=path.substring(3);
					 System.out.println(realPath+factPath);
					 File file=new File(realPath+factPath);
					 if(file.exists()){
						 file.delete();
					 }
				 }
				 this.carService.deleteCar(carVo);
				 map.put("msg", "添加成功");
			} catch (Exception e) {
				e.printStackTrace();
				 map.put("msg", "添加失败");
			}
			return  map;
		}
}
